<script setup lang="ts">
import AIUtil from "@/components/utils/AiUtile/Index.vue"
import CardAuthorInfo from "@/components/communal/Card/card-author-info.vue";
import {ref, toRefs, onBeforeUnmount, shallowRef, onMounted} from "vue"
import { useRouter, useRoute} from "vue-router";
import { Editor } from '@wangeditor/editor-for-vue'
import { SettingOutlined, EditOutlined, EllipsisOutlined, RollbackOutlined} from '@ant-design/icons-vue';
import type { TreeProps } from 'ant-design-vue';
import {message} from "ant-design-vue";
import {useRequest} from "vue-hooks-plus/es";
import {
  postBlogGetArticleById,
  postCurriculumGetCurriculumById,
  postCurriculumGetLearningCurriculum, postMangeGetUserByUserId,
  postMangeGetUserByUsername
} from "@/apis/student";
import {getContentDirTree} from "@/config";

const router=useRouter()
const route=useRoute()
let loading = ref<boolean>(true)

//路由请求设置
// 路由传参
const {query} = toRefs(route)
const goBack = () => {
  router.go(-1)
}

//编辑器设置
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('<p></p>')

const mode = 'default'
// 模拟 ajax 异步获取内容
onMounted(() => {
  curriculumF()
})
//工具栏配置
const toolbarConfig = {}
//编辑器配置
const editorConfig = {
  placeholder: '等待加载...',
  readOnly: true,
  scroll: false
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor:any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//目录设置
const treeData: TreeProps['treeData'] = getContentDirTree(valueHtml.value);
const expandedKeys = ref<string[]>([]);
if (treeData){
  expandedKeys.value = treeData.map((item:any)=>item.key)
}
const selectedKeys = ref<string[]>([]);
// 课程
let titleName = ref('课程')
let user = ref('user')
let intro = ref('intro')
let userImage = ref('userImg')
const curriculumF = async () => {
  if(!query.value.type){
    return;
  }
  let res:any = null;
  let manger:any = null;
  let content:string = 'curriculumContent'
  let title:string = 'curriculumName'
  let userName:string = 'nickname'
  let description:string = 'userIntro'
  let userImg:string = 'userImg'
  // 数据获取
  switch (query.value.type){
    case "curriculum":
      if (query.value.id)
      try {
        res = await postCurriculumGetCurriculumById({ id: +query.value.id || 0})
        content='curriculumContent'
        title = 'curriculumName'
        manger = await postMangeGetUserByUsername({userName: res.data.curriculumFrom})
        loading.value = false
      } catch (e) {
        loading.value = false
        return
      }
      break;
    case "note":
      console.log("读取笔记")
      break;
    case "article":
      if (query.value.id)
      try {
        res = await postBlogGetArticleById({articleId: +query.value.id})
        content = 'articleContent'
        title = 'articleName'
        manger = await postMangeGetUserByUserId({id: +res.data.userId})
        userName = 'nickname'
        description = 'userIntro'
        loading.value = false
      } catch (e) {
        loading.value = false
        return
      }
      break;
    default:
      goBack()
      break;
  }
  if(res && res.code !== 200){
    valueHtml.value = res.data[content]
    titleName.value = res.data[title]
    if (!manger){
      return
    }
    user.value = manger.data[userName]
    intro.value = manger.data[description]
    userImage.value = manger.data[userImg]
  }
}

</script>

<template>
  <a-layout class="read-layout" :style="{background: '#fcfcfc'}">
    <a-row style="height: 100%" :gutter="16">
      <a-col :span="6" style="height: 100%">
        <a-flex vertical gap="16">
          <CardAuthorInfo></CardAuthorInfo>
          <a-card >

<!--            <template #actions>-->
<!--              <setting-outlined key="setting" />-->
<!--              <edit-outlined key="edit" />-->
<!--              <ellipsis-outlined key="ellipsis" />-->
<!--            </template>-->
<!--            <a-card-meta :title=user :description=intro>-->
<!--              <template #avatar>-->
<!--                <a-avatar :src=userImage />-->
<!--              </template>-->
<!--            </a-card-meta>-->
          </a-card>
          <a-card :loading="loading">
            <a-card-meta title="目 录"></a-card-meta>
            <a-spin :spinning="loading">
              <a-directory-tree
                  v-model:expandedKeys="expandedKeys"
                  v-model:selectedKeys="selectedKeys"
                  multiple
                  :tree-data="treeData"
              ></a-directory-tree>
            </a-spin>
          </a-card>
        </a-flex>
      </a-col>
      <a-col :span="18" style="height: 100%">
        <h1 class="read-content-title">{{ titleName }}</h1>
        <a-spin :spinning="loading">
          <a-card>
            <Editor
                style="min-height: 500px; overflow-y: hidden;"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
            />
          </a-card>
        </a-spin>
      </a-col>
    </a-row>
    <AIUtil></AIUtil>
    <a-float-button type="default" @click="goBack" :style="{left: '72px',}">
      <template #icon>
        <RollbackOutlined />
      </template>
    </a-float-button>
  </a-layout>
</template>

<style lang="scss" scoped>
.read-layout{
  width: 100%;
  min-height: 100vh;
  padding: 1rem 10%;
}
.read-content-title{
  width: 100%;
  height: auto;
  padding: 1rem;
  margin-bottom: .5rem;
  border-radius: 5px;
  border: .5px solid #f2f2f2;
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  background: #fff;
}
</style>
